package com.fulin.security;

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
*
* @description 
* @auther fulin16@crnet.com.hk
* @since 2020年1月14日 上午10:51:10
*
*/
public class AESUtils {
	/**
	 * 用AES算法加密
	 * @param encodeRules
	 * @param content
	 * @return
	 */
	public static String Encode(String encodeRules,String content) {
		try {
			//构造秘钥生成器,指定AES算法，不区分大小写
			KeyGenerator keyGen = KeyGenerator.getInstance("AES");
			//根据ecnodeRules规则初始化秘钥生成器
			//生成一个128位的随机源，根据传入的字节数组
			keyGen.init(128,new SecureRandom(encodeRules.getBytes()));
			//生成原始对称秘钥
			SecretKey original_key = keyGen.generateKey();
			//获取原始对称秘钥的字节数组
			byte[] raw = original_key.getEncoded();
			//根据字节数组生成AES秘钥
			SecretKey key = new SecretKeySpec(raw,"AES");
			//根据指定算法AES生成密码器
			Cipher cipher = Cipher.getInstance("AES");
			//初始化密码器,第一个参数为加密或者解密
			cipher.init(Cipher.ENCRYPT_MODE, key);
			//获取加密内容的字节数组
			byte[] byte_encode = content.getBytes("utf-8");
			//对数据进行加密
			byte[] byte_AES = cipher.doFinal(byte_encode);
			//将加密内容转换为字符串
			return new String(new BASE64Encoder().encode(byte_AES));
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 用AES算法解密
	 * @param encodeRules
	 * @param content
	 * @return
	 */
	public static String decode(String encodeRules,String content) {
		try {
			//构造密钥生成器，指定为AES算法，不区分大小写
			KeyGenerator keygen = KeyGenerator.getInstance("AES");
			//根据econdeRules规则初始化密钥生成器，生成一个128位的随机源，根据传入的字节数组
			keygen.init(128, new SecureRandom(encodeRules.getBytes()));
			//产生原始密钥对
			SecretKey original_key = keygen.generateKey();
			//获得原始对称密钥的字节数组
			byte[] raw = original_key.getEncoded();
			//根据字节数组生成AES密钥
			SecretKey key = new SecretKeySpec(raw,"AES");
			//根据指定算法AES生成密码器
			Cipher cipher = Cipher.getInstance("AES");
			//初始化密码器，第一个参数为加密或者解密操作
			cipher.init(Cipher.DECRYPT_MODE, key);
			//将加密并编码后的内容解析成字节数组
			byte[] byte_content = new BASE64Decoder().decodeBuffer(content);
			//解密
			byte[] byte_decode = cipher.doFinal(byte_content);
			return new String(byte_decode,"utf-8");
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		String result = AESUtils.Encode("fulin", "fulin first test of AES");
		System.out.println(result);
		String decode = AESUtils.decode("fulin", result);
		System.out.println(decode);
	}
}
